﻿using System.Collections.Generic;
using UnityEngine;

namespace CWM.Skinn
{
    public static partial class SkinnEx
    {
        public static SkinnedMeshRenderer CloneMerged(this SkinnedMeshRenderer source, Transform transform, out List<Transform> createdObjects,
            bool bindpose,
            bool optimize)
        {
            createdObjects = new List<Transform>();
            var root = transform;
            if (!HasMinimumRequirements(source, true)) return null;
            SkinnedMeshRenderer smr = null;
            if (optimize) source.CloneOptimzeBones(out smr);
            if (!smr) smr = source.Clone() as SkinnedMeshRenderer;

            smr.transform.SetParent(root);
            smr.transform.CopyLocalSpace(source.transform);

            if (bindpose) smr.BakeAndBindpose();

            Transform[] bones;
            List<Transform> newTransforms;
            root.MergeCloneIfNeeded(source.bones, out bones, out newTransforms);

            smr.sharedMesh.bindposes = bindpose ? bones.GetBindposes() : smr.sharedMesh.bindposes;
            smr.bones = bones;
            smr.rootBone = bones.HasTrueRootBone() ? bones.FindMinHierarchicalOrder() : null;
            smr.SetBounds();
            
            createdObjects.Add(smr.transform);
            if (newTransforms.Count > 0) createdObjects.AddRange(newTransforms);
            return smr;
        }

        public static SkinnedMeshRenderer CloneMerged(this SkinnedMeshRenderer source, Transform transform, out List<Transform> createdObjects)
        {
            createdObjects = new List<Transform>();
            var root = transform;
            if (!HasMinimumRequirements(source, true)) return null;
            SkinnedMeshRenderer smr;
            smr = source.Clone(true) as SkinnedMeshRenderer;
            smr.sharedMesh = source.sharedMesh;
            smr.transform.SetParent(root);
            smr.transform.CopyLocalSpace(source.transform);

            Transform[] bones;
            List<Transform> newTransforms;
            root.MergeCloneIfNeeded(source.bones, out bones, out newTransforms);

            smr.bones = bones;
            smr.rootBone = bones.HasTrueRootBone() ? bones.FindMinHierarchicalOrder() : null;
            smr.SetBounds();

            createdObjects.Add(smr.transform);
            if (newTransforms.Count > 0) createdObjects.AddRange(newTransforms);
            return smr;
        }
    }
}
